package com.jyu.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.jyu.reggie.common.BaseContext;
import com.jyu.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Slf4j
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    public static final AntPathMatcher pathMatcher = new AntPathMatcher();

    /**
     * @description: 资源访问过滤器，禁止未登录对象查看内容
     * @param servletRequest
 * @param servletResponse
 * @param filterChain
     * @return: void
     * @date: 2023/7/26 22:06
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        log.info("拦截到请求：{}",requestURI);

        String[] urls = {
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login",

        };

        boolean check = false;
        for (String url : urls) {
            boolean match = pathMatcher.match(url, requestURI);
            if( match ) {
                check = match;
                break;
            }
        }

        if ( check == true) {
            log.info("本次请求{}不需要处理",requestURI);
            filterChain.doFilter(request, response);
            return;
        }


        // 管理端： 判断当前是否有 employe 登录。
        if( request.getSession().getAttribute("employee") != null) {
            log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("employee"));

            // 获取当前登陆的  employee id
            Long empId = (Long) request.getSession().getAttribute("employee");

            //  为当前线程设置 id
            BaseContext.setCurrentId(empId);

            // 放行
            filterChain.doFilter(request, response);
            return;
        }

        //  客户端判断当前 是否已有用户登陆。
        if( request.getSession().getAttribute("user") != null) {
            log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("user"));

            Long userId = (Long) request.getSession().getAttribute("user");
            // 有用户登陆，则为当前线程设置 id
            BaseContext.setCurrentId(userId);

            filterChain.doFilter(request, response);
            return;
        }

        log.info("用户未登录");

        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }



}
